import DbSearcher, { QueryType } from "czdb";
import path from "path";
import { fileURLToPath } from "url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const rootDir = path.join(__dirname, "../..");

class CzdbService {
  constructor() {
    this.ipv4Searcher = null;
    this.ipv6Searcher = null;
  }

  initialize(ipv4DbPath, ipv6DbPath, key) {
    try {
      // 如果存在旧实例，先销毁
      this.destroy();

      // 解析相对路径
      const resolveDbPath = (dbPath) => {
        if (!dbPath) return null;
        return dbPath.startsWith(".") ? path.resolve(rootDir, dbPath) : dbPath;
      };

      const resolvedIpv4Path = resolveDbPath(ipv4DbPath);
      const resolvedIpv6Path = resolveDbPath(ipv6DbPath);

      console.log("初始化数据库路径:");
      console.log("IPv4路径:", resolvedIpv4Path);
      console.log("IPv6路径:", resolvedIpv6Path);

      // 创建新实例
      if (resolvedIpv4Path) {
        this.ipv4Searcher = new DbSearcher(
          resolvedIpv4Path,
          QueryType.BTREE,
          key
        );
      }
      if (resolvedIpv6Path) {
        this.ipv6Searcher = new DbSearcher(
          resolvedIpv6Path,
          QueryType.BTREE,
          key
        );
      }

      return true;
    } catch (error) {
      console.error("CZDB初始化失败:", error);
      return false;
    }
  }

  destroy() {
    try {
      if (this.ipv4Searcher) {
        this.ipv4Searcher.close();
        this.ipv4Searcher = null;
      }
      if (this.ipv6Searcher) {
        this.ipv6Searcher.close();
        this.ipv6Searcher = null;
      }
    } catch (error) {
      console.error("CZDB销毁失败:", error);
    }
  }

  searchIp(ip) {
    try {
      // 清理IP地址
      let cleanIp = ip.trim();
      
      // 移除端口号（如果有）
      if (cleanIp.includes(":")) {
        const parts = cleanIp.split(":");
        cleanIp = parts[0];
      }
      
      // 处理 IPv6 格式的地址
      if (cleanIp.includes("::ffff:")) {
        cleanIp = cleanIp.replace("::ffff:", "");
      }

      // 简单的IPv4/IPv6判断
      const isIpv4 = cleanIp.indexOf(":") === -1;
      let result;

      if (isIpv4 && this.ipv4Searcher) {
        result = this.ipv4Searcher.search(cleanIp);
      } else if (!isIpv4 && this.ipv6Searcher) {
        result = this.ipv6Searcher.search(cleanIp);
      } else {
        throw new Error(`不支持的IP类型或未初始化对应的搜索器: ${cleanIp}`);
      }

      if (!result) {
        return null;
      }

      // 解析返回的字符串格式 "国家–省份–城市 ISP"
      // 先用制表符分割位置信息和ISP
      const [locationStr, isp = ""] = result.split("\t");
      // 再用中文破折号分割位置信息
      const location = locationStr.split("–");

      return {
        country: location[0] || "",
        region: location[3] || "", // 如果有区域信息的话
        province: location[1] || "",
        city: location[2] || "",
        isp: isp.trim(),
      };
    } catch (error) {
      console.error("IP查询失败:", error);
      throw error;
    }
  }

  isInitialized() {
    return this.ipv4Searcher !== null || this.ipv6Searcher !== null;
  }
}

// 创建单例实例
const czdbService = new CzdbService();
export default czdbService;
